<template>
  <PageWrapper dense>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Space>
          <a-button
            type="primary"
            :pre-icon="IconEnum.ADD"
            @click="handleAdd"
            v-auth="'system:tenant:add'"
            >新增租户</a-button
          >
          <a-button
            class="<sm:hidden"
            type="primary"
            danger
            :preIcon="IconEnum.DELETE"
            v-auth="'system:tenant:remove'"
            :disabled="!selected"
            @click="multipleRemove(tenantRemove)"
            >选中删除</a-button
          >
          <OpenSelector v-model:value="openType" />
        </Space>
      </template>
      <template #toolbar>
        <a-button
          class="<sm:hidden"
          :preIcon="IconEnum.EXPORT"
          color="warning"
          ghost
          v-auth="'system:tenant:export'"
          @click="downloadExcel(tenantExport, '租户信息')"
          >导出数据</a-button
        >
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <TableSwitch
            v-model="record.status"
            :disabled="record.tenantId === 1"
            :api="() => tenantStatusChange(record)"
            :custom-content="
              (newStatusStr: string) => `确认${newStatusStr}租户[${record.companyName}]吗?`
            "
            :reload="reload"
          />
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '修改',
                icon: IconEnum.EDIT,
                type: 'primary',
                ghost: true,
                auth: 'system:tenant:edit ',
                onClick: handleEdit.bind(null, record),
                ifShow: record.tenantId !== 1,
              },
              {
                label: '同步',
                icon: IconEnum.SYNC,
                type: 'success',
                ghost: true,
                auth: 'system:tenant:edit ',
                onClick: handleSync.bind(null, record),
                ifShow: record.tenantId !== 1,
              },
              {
                label: '删除',
                icon: IconEnum.DELETE,
                type: 'error',
                ghost: true,
                auth: 'system:tenant:delete',
                ifShow: record.tenantId !== 1,
                onClick: handleRemove.bind(null, record),
              },
            ]"
        /></template>
      </template>
    </BasicTable>
    <TenantModal @register="registerModal" @reload="reloadWithCallback" />
    <TenantDrawer @register="registerDrawer" @reload="reloadWithCallback" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '@/components/Page';
  import {
    tenantList,
    tenantRemove,
    tenantSyncPackage,
    tenantStatusChange,
    tenantExport,
  } from '@/api/system/tenant';
  import { BasicTable, useTable, TableAction, TableSwitch } from '@/components/Table';
  import { columns, formSchemas } from './tenant.data';
  import { IconEnum } from '@/enums/appEnum';
  import { Space } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { downloadExcel } from '@/utils/file/download';
  import TenantModal from './TenantModal.vue';
  import { useModal } from '@/components/Modal';
  import TenantDrawer from './TenantDrawer.vue';
  import { useDrawer } from '@/components/Drawer';
  import { useTenantStore } from '@/store/modules/tenant';
  import { useOpenType, OpenSelector } from '@/components/OpenWindow';

  defineOptions({ name: 'Tenant' });

  const [registerTable, { reload, reloadWithCallback, selected, multipleRemove }] = useTable({
    rowSelection: {
      type: 'checkbox',
      getCheckboxProps: (record: Recordable) => ({
        disabled: record.tenantId === 1,
      }),
    },
    rowKey: 'tenantId',
    showIndexColumn: false,
    useSearchForm: true,
    formConfig: {
      schemas: formSchemas,
      baseColProps: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 8,
      },
      name: 'tenant',
      labelWidth: 100,
      // 日期选择格式化
      fieldMapToTime: [
        [
          'createTime',
          ['params[beginTime]', 'params[endTime]'],
          ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
        ],
      ],
    },
    columns,
    api: tenantList,
    actionColumn: {
      width: 260,
      fixed: 'right',
      title: '操作',
      key: 'action',
    },
  });

  const [registerModal, { openModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const { openType, openWindow } = useOpenType('tenant-open', 'drawer', {
    modal: openModal,
    drawer: openDrawer,
  });

  function handleAdd() {
    openWindow(true, { update: false });
  }
  function handleEdit(record: Recordable) {
    openWindow(true, { update: true, record });
  }

  const { createConfirm } = useMessage();
  async function handleSync(record: Recordable) {
    createConfirm({
      iconType: 'warning',
      title: '同步套餐',
      content: `是否同步[${record.companyName}]的套餐?`,
      async onOk() {
        const { tenantId, packageId = '0' } = record;
        await tenantSyncPackage(tenantId, packageId);
        await reload();
      },
    });
  }
  const { initTenant } = useTenantStore();
  function handleRemove(record: Recordable) {
    createConfirm({
      iconType: 'warning',
      title: '删除租户',
      content: `是否删除租户[${record.companyName}] ID:[${record.tenantId}]?`,
      async onOk() {
        await tenantRemove([record.tenantId]);
        await reload();
        // 重新获取租户信息
        await initTenant();
      },
    });
  }
</script>
<style scoped></style>
